/*
 * @(#)org.example 2020/3/25/0025
 *
 * Copy Right@ 人人译视界
 */


package org.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/3/25/0025
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class ScatteringAndGatheringDemo {
	public static void main(String[] args) throws IOException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

		serverSocketChannel.socket().bind(inetSocketAddress);

		ByteBuffer[] buffers = new ByteBuffer[2];
		buffers[0] = ByteBuffer.allocate(5);
		buffers[1] = ByteBuffer.allocate(3);

		SocketChannel socketChannel = serverSocketChannel.accept();
		int limitLength = 8;//假定从客户端接收8字节
		while(true) {
			int byteRead = 0;
			while(byteRead < limitLength) {
				long l = socketChannel.read(buffers);
				byteRead += l;
				System.out.println("byteRead=" + byteRead);
				Arrays.asList(buffers).stream().map(buf -> "position=" + buf.position() + ",limit=" + buf.limit()).forEach(System.out::println);
			}

			Arrays.asList(buffers).stream().forEach(buf -> buf.flip());

			long byteWrite = 0;
			while(byteWrite < limitLength) {
				long l = socketChannel.write(buffers);
				byteWrite += l;
			}

			Arrays.asList(buffers).stream().forEach(buf -> buf.clear());

			System.out.println("byteRead=" + byteRead + ",byteWrite=" + byteWrite);
		}
	}
}
